
<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home/Home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>容器管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 信息面板 -->
        <el-card class="cardBox">
            <!-- 标题 -->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: large;">容器管理</span>
            </div>
            <!-- 容器列表 -->
            <div>
                <!-- bug：如果没有主机，页面刷新不出来 -->
                <el-table height="720px" :key="tableKey"
                    :data="containers.filter(data => !search || data.containerName.toLowerCase().includes(search.toLowerCase()) || !data)"
                    style="width: 100%">
                    <!-- <el-table-column fixed prop="status" label="主机状态" width="100" :filters="[{
                        text: '存活', value: 'alive'
                    }, { text: '掉线', value: 'dead' }]" :filter-method="filterStatus" filter-placement="bottom-end">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 'alive' ? '' : 'success'" disable-transitions>{{
                                scope.row.status
                            }}</el-tag>
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="simpleId" label="容器Id" width="130" />
                    <el-table-column prop="containerName" label="容器名称" width="120" />
                    <el-table-column prop="imageName" label="镜像名称" width="250" />
                    <el-table-column prop="name" label="主机名称" width="140" />
                    <el-table-column label="状态" width="80">
                        <template #default="scope">
                            <el-tag type="success" size="small" v-if="scope.row.status == 'running'"
                                effect="dark">Running</el-tag>
                            <el-tag type="danger" size="small" v-if="scope.row.status == 'exited'"
                                effect="dark">Stopped</el-tag>
                            <el-tag type="warning" size="small" v-if="scope.row.status == 'paused'"
                                effect="dark">Paused</el-tag>
                        </template>

                    </el-table-column>

                    <el-table-column prop="createTime" label="创建时间" sortable />
                    <el-table-column align="right" width="340">
                        <template #header>
                            <el-input v-model="search" size="small" style="width: 250px;" placeholder="查询容器" />
                        </template>
                        <template #default="scope">

                            <el-button style="color: green; margin-right: -3%;" type="text"
                                v-if="scope.row.status == 'exited'" icon="el-icon-video-play"
                                @click="containerStart(scope.row)">运行</el-button>
                            <el-button style=" margin-right: -3%;" type="text" v-if="scope.row.status == 'paused'"
                                icon="el-icon-video-play" @click="containerStart(scope.row)" disabled>运行</el-button>
                            <el-button style="color: red;  margin-right: -3%;" type="text"
                                v-if="scope.row.status == 'running'" icon="el-icon-circle-close"
                                @click="containerStop(scope.row)">停止</el-button>
                            <el-divider direction="vertical"></el-divider>

                            <el-button style=" margin-right: -3%;" type="text" v-if="scope.row.status == 'running'"
                                icon="el-icon-video-pause" @click="containerPause(scope.row)">暂停</el-button>

                            <el-button style=" margin-right: -3%;" type="text" v-if="scope.row.status == 'paused'"
                                icon="el-icon-video-pause" @click="containerUnpause(scope.row)">开启</el-button>

                            <el-button style=" margin-right: -3%;" type="text" v-if="scope.row.status == 'exited'" disabled
                                icon="el-icon-video-pause" @click="containerPause(scope.row)">暂停</el-button>
                            <el-divider direction="vertical"></el-divider>


                            <el-button type="text" icon="el-icon-document" @click="containerLog(scope.row)">日志</el-button>
                            <el-divider direction="vertical"></el-divider>
                            <el-dropdown size="mini">
                                <span class="el-dropdown-link">
                                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item>重命名</el-dropdown-item>
                                    <el-dropdown-item>删除</el-dropdown-item>
                                    <el-dropdown-item @click.native="toInfo(scope.row)">管理</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 日志侧边栏 -->
            <el-drawer :title="logDrawer.title" :visible.sync="logDrawer.show" :direction="rtl"
                :before-close="logDrawerClose">
                <!-- <el-divider /> -->
                <div style="margin-left: 20px; margin-right: 20px;">
                    <el-input id="logInput" style="background-color: lightgray; color: black;" type="textarea" :rows="40"
                        v-model="logDrawer.logInfo" readonly>
                    </el-input>
                </div>
            </el-drawer>
        </el-card>
    </div>
</template>

<script>
import { getAllContainer, startContainer, stopContainer, pauseContainer, unpauseContainer, renameContainer, removeContainer } from '../../api/userMG';
import { toDateTime } from '../../utils/util';
export default {
    name: "ContainersMannagement",
    // 模块数据
    data() {
        return {
            tableKey: 0,
            websocket: null,
            total: 0,
            running: 0,
            stopped: 0,
            paused: 0,
            containers: [],
            search: '',
            logDrawer: {
                show: false,
                logInfo: '',
            },

        };
    },
    methods: {
        getBaseData() {
            getAllContainer().then(res => {
                if (res.code == 0) {
                    this.total = res.data.total
                    this.running = res.data.running
                    this.stopped = res.data.stopped
                    this.paused = res.data.paused
                    var cards = res.data.containers
                    for (var i = 0; i < cards.length; i++) {
                        var c = cards[i].container
                        var Obj = {
                            key: cards[i].key,
                            name: cards[i].name,
                            id: cards[i].id,
                            containerName: c.Names[0].replace(/\//g, ""),
                            containerId: c.Id,
                            simpleId: c.Id.substring(0, 12),
                            imageName: c.Image,
                            status: c.State,
                            createTime: toDateTime(c.Created)
                        }
                        this.containers.push(Obj)
                    }
                } else {
                    this.$message.error(res.msg);
                }
            })
            this.tableKey = Math.random()
        },
        containerStart(row) {
            var params = {
                key: row.key,
                id: row.containerId
            }
            startContainer(params).then(res => {
                if (res.code == 0) {
                    this.$message.success("容器【" + row.simpleId + "】启动成功！")
                    this.getBaseData()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        containerStop(row) {
            var params = {
                key: row.key,
                id: row.containerId
            }
            stopContainer(params).then(res => {
                if (res.code == 0) {
                    this.$message.success("容器【" + row.simpleId + "】停止成功！")
                    this.getBaseData()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        containerPause(row) {
            var params = {
                key: row.key,
                id: row.containerId
            }
            pauseContainer(params).then(res => {
                if (res.code == 0) {
                    this.$message.success("容器【" + row.simpleId + "】暂停成功！")
                    this.getBaseData()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        containerUnpause(row) {
            var params = {
                key: row.key,
                id: row.containerId
            }
            unpauseContainer(params).then(res => {
                if (res.code == 0) {
                    this.$message.success("容器【" + row.simpleId + "】取消暂停成功！")
                    this.getBaseData()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        containerLog(row) {
            this.logDrawer.show = true
            this.logDrawer.title = "容器【" + row.simpleId + "】的日志"
            var params = {
                key: row.key,
                id: row.containerId
            }
            const socket = new WebSocket('ws://localhost:8081/api/ws/log/' + params.key + '/' + params.id);
            socket.onopen = () => {
                console.log('WebSocket连接已建立');
            }
            socket.onmessage = (event) => {
                this.logDrawer.logInfo += event.data
                this.$nextTick(() => {
                    setTimeout(() => {
                        const textarea = document.getElementById('logInput');
                        textarea.scrollTop = textarea.scrollHeight;
                    }, 13)
                })
            }
            this.websocket = socket
        },
        logDrawerClose() {
            this.logDrawer.show = false
            this.logDrawer.logInfo = ''
            this.websocket.close()
        },
        toInfo(row) {
            this.$router.push({ path: '/container/containerInfo?key=' + row.key + '&id=' + row.containerId });
        },
    },

    created() {
        this.getBaseData()

    },
    beforeDestroy() {
        this.websocket.close()
    },

};
</script>

<style scoped>
.cardBox {
    margin-top: 30px;
    width: 95%;
    height: 100%;
    margin-left: 1%;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 13px;
}
</style>
